<template>
  <div class="container">
    <div class="partial-title">
      <el-select v-model="select" placeholder="请选择">
        <el-option label="标题" value="title"></el-option>
      </el-select>
      <el-input
        placeholder="请输入内容"
        v-model="searchField"
        class="input-with-select"
      >
        <el-button
          slot="append"
          icon="el-icon-search"
          @click="getList()"
        ></el-button>
      </el-input>
      <div class="custom-btn" @click="handleAdd()">新增</div>
    </div>
    <el-table :data="tableData" border style="width: 100%; margin-top: 1.75vw">
      <el-table-column fixed prop="id" label="ID"> </el-table-column>
      <el-table-column prop="title" label="标题"> </el-table-column>
      <el-table-column prop="createDate" label="加入时间">
        <template slot-scope="scope">
          {{
            scope.row.createDate
              .replace("T", " ")
              .replace("Z", " ")
              .substring(0, 19)
          }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template slot-scope="scope">
          <el-button
            @click="handleEditor(scope.row)"
            type="primary"
            size="small"
            >编辑</el-button
          >
          <el-button type="danger" size="small" @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :page-size="pageSize"
      :current-page.sync="pageNo"
      :total="total"
      layout="prev, pager, next"
      style="right: 1.5vw; position: absolute"
    >
    </el-pagination>
    <el-dialog
      :title="type == 'add' ? '新增' : '编辑'"
      :visible.sync="formShow"
    >
      <el-form :model="form" :rules="rules" ref="form" label-position="left">
        <el-form-item
          label="标题"
          :label-width="defaultLabelWidth"
          prop="title"
          maxlength="20"
        >
          <el-input
            v-model="form.title"
            autocomplete="off"
            style="width: 15vw"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="发布"
          :label-width="defaultLabelWidth"
          prop="publish"
          maxlength="20"
        >
          <el-switch
            v-model="form.publish"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0"
          >
          </el-switch>
        </el-form-item>
        内容
        <div
          ref="editor"
          id="editor"
          style="text-align: left; margin-top: 1.5vw"
        ></div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancle('form')">取 消</el-button>
        <el-button type="primary" @click="submit(type)">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style>
</style>

<script>
import Editor from "wangeditor";
export default {
  data() {
    let baseImgurl = window.location.origin;
    return {
      editor: null,
      baseImgurl,
      total: 0,
      pageNo: 1,
      pageSize: 9,
      formShow: false,
      type: "add",
      select: "title",
      searchField: "",
      defaultLabelWidth: "6vw",
      tableData: [],
      form: {
        title: "",
        content: "",
        publish: 0,
      },
      rules: {
        title: [
          {
            required: true,
            message: "标题不能为空！",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    switch() {},
    getList() {
      let that = this;
      let query = {
        pageNo: this.pageNo,
        pageSize: this.pageSize,
      };
      query.role = this.role;
      query[this.select] = this.searchField;
      let queryStr = this.$query.stringify(query);
      this.$axios.get(`/api/v1/announces?${queryStr}`).then((data) => {
        that.total = data.totalCount;
        that.pageNo = data.pageNo;
        that.tableData = data.announces;
      });
    },
    ediotrInit() {
      let message = this.$message;
      let that = this;
      this.editor = new Editor(document.getElementById("editor"));
      this.editor.config.pasteFilterStyle = false;
      this.editor.config.onchange = (html) => {
        that.form.content = html;
      };
      this.editor.config.customUploadImg = function (files, insert) {
        if (files.length > 1) {
          message.error("每次只能上传1张图片！");
          return;
        }
        const isIMAGE =
          files[0].type === "image/jpg" ||
          "image/jpeg" ||
          "image/gif" ||
          "image/png";
        const isLt800K = files[0].size / 1024 < 1024;
        if (!isIMAGE) {
          message.error("上传图片只支持jpg/jpeg/gif/png格式!");
          return;
        }
        if (!isLt800K) {
          message.error("上传图片大小不能超过 1M!");
          return;
        }
        let formdata = new FormData();
        formdata.append("file", files[0]);
        that.$axios
          .post("/api/v1/upload", formdata)
          .then((res) => {
            insert(that.baseImgurl + res.url);
          })
          .catch((e) => {
            message.error(e.data.message);
          });
      };
      this.editor.create();
    },
    handleAdd() {
      let that =this;
      this.type = "add";
      this.form.title = "";
      this.form.content = "";
      this.formShow = true;
      if (!this.editor) {
        setTimeout(function () {
          that.ediotrInit();
          that.editor.txt.html("");
        }, 300);
      } else {
        this.editor.txt.html("");
      }
    },
    handleEditor(row) {
      this.type = "editor";
      this.form = row;
      this.formShow = true;
      let that = this;
      if (!this.editor) {
        setTimeout(function () {
          that.ediotrInit();
          that.editor.txt.html(row.content);
        }, 300);
      } else {
        this.editor.txt.html(row.content);
      }
    },
    handleDelete(row) {
      let that = this;
      this.$axios
        .delete("/api/v1/announce?id=" + row.id)
        .then((data) => {
          if (data.result) {
            that.$message.success({
              message: "删除成功",
              center: true,
              offset: screen.availHeight * 0.32,
              duration: 1200,
            });
            that.getList();
          }
        })
        .catch((err) => {
          that.$message.error({
            message: err.data.message,
            center: true,
            offset: screen.availHeight * 0.32,
            duration: 1200,
          });
        });
    },
    cancle(formName) {
      this.$refs[formName].resetFields();
      this.formShow = false;
    },
    submit(type) {
      let that = this;
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let request =
            type == "add"
              ? this.$axios.post("/api/v1/announce", this.form)
              : this.$axios.put("/api/v1/announce", this.form);

          request
            .then((data) => {
              if (data.result) {
                that.$message.success({
                  message: "操作成功",
                  center: true,
                  offset: screen.availHeight * 0.32,
                  duration: 1200,
                });
                this.$refs["form"].resetFields();
                this.editor.txt.html("");
                that.getList();
                this.formShow = false;
              }
            })
            .catch((err) => {
              that.$message.error({
                message: err.data.message,
                center: true,
                offset: screen.availHeight * 0.32,
                duration: 1200,
              });
            });
        }
      });
    },
  },
  computed: {},
  beforeMount() {
    this.$axios.post("/api/v1/user/verified");
    this.getList();
  },
};
</script>
